package com.wise.service.cms.content.pagedecorate;

import com.wise.entities.content.Decorate;
import com.wise.framework.basic.DateTimeUtil;
import com.wise.framework.daomodel.DaoOne4Update;
import com.wise.framework.daomodel.DaoSave;
import com.wise.framework.exception.LogicException;
import com.wise.framework.session.CurrentUserId;
import com.wise.framework.session.GetAcceptLanguage;
import com.wise.summer.v1.cms.content.pagedecorate.UpdatePageDecorateById;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.sql.Timestamp;

import static com.wise.model.content.ContentErrMsgs.Err_000500000004;
import static com.wise.model.content.ContentErrMsgs.Err_000500000027;


@Service
@SummerService
public class UpdatePageDecorateService implements SummerServiceBean<UpdatePageDecorateById> {

    @Override
    public void sum(UpdatePageDecorateById model) {
        Decorate decorate = DaoOne4Update.s(Decorate.class, model.getId(), Err_000500000004);
        String lang = GetAcceptLanguage.s(true);
        // 别名转换
        model.setAlias(PageDecorateTools.toNullAlias(model.getAlias()));
        // 别名不许重复
        if (model.getAlias() != null && !model.getAlias().equals(decorate.getAlias())) {
            if (PageDecorateTools.checkAlias(model.getAlias())) {
                throw new LogicException(this.getClass(), Err_000500000027);
            }
        }
        decorate.setAlias(model.getAlias());

        Timestamp now = DateTimeUtil.timestampNow();

        decorate.setLang(lang);
        if (!StringUtils.isEmpty(model.getTitle())) {
            decorate.setTitle(model.getTitle());
        }
        if (null != model.getState()) {
            if (model.getState() == 0) {
                //状态为0，则保存为草稿
                decorate.setContent(model.getContent());
            } else if (model.getState() == 1) {
                //状态为1，则保存为正式内容
                decorate.setContent(model.getContent());
                decorate.setPublicContent(model.getContent());
            }
        }
        if (!StringUtils.isEmpty(model.getModule())) {
            decorate.setModule(model.getModule());
        }
        if (!StringUtils.isEmpty(model.getImg())) {
            decorate.setImg(model.getImg());
        }
        //更新修改人信息
        decorate.setLastUpdateBy(CurrentUserId.s(true));
        decorate.setLastUpdateDate(now);

        decorate.setSeoTitle(model.getSeoTitle());
        decorate.setSeoDescribe(model.getSeoDescribe());

        decorate.setPageTitle(model.getPageTitle());

        DaoSave.s(decorate);

        model.setSummerResult(decorate);
    }
}
